package com.st.controller;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;

import com.st.entity.User;
import com.st.service.IUserService;
import com.st.service.impl.UserServiceImpl;

@WebServlet("/user.do")
@MultipartConfig
public class UserServlet extends BaseServlet {
	private IUserService userService = new UserServiceImpl();

	public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
		System.out.println("logout");
		// 获取参数（不需要）
		// 业务
		HttpSession session = request.getSession();
		session.invalidate();
		// 返回结果
		// 跳转到主页
		response.sendRedirect("index.jsp");
	}

	public void login(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		System.out.println("login");
		// 获取参数
		String username = request.getParameter("username");
		String password = request.getParameter("password");

		User loginUser = new User();
		loginUser.setUsername(username);
		loginUser.setPassword(password);

		// 业务处理
		User user = userService.login(loginUser);
		// 返回结果
		if (user != null) {
			// 登录成功
			// 保存登录状态
			HttpSession session = request.getSession();
			session.setAttribute("user", user);

			// 跳转到主页
			response.sendRedirect("index.jsp");
		} else {
			// 登录失败
			request.setAttribute("error", "账号或密码错误");
			// 返回登录页面
			request.getRequestDispatcher("login.jsp").forward(request, response);
		}
	}

	public void modifyPwd(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		// 获取参数
		String oldpassword = request.getParameter("oldpassword");
		String newpassword = request.getParameter("newpassword");
		String newpassword2 = request.getParameter("newpassword2");

		// 获取当前登录用户的id
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("user");// 需要强制转换

		if (user == null) {
			// 用户没有登录
			response.sendRedirect("login.jsp");
			return;
		}

		// 业务处理
		int res = userService.modifyPwd(user, oldpassword, newpassword, newpassword2);
		// 结果
		if (res > 0) {
			// 修改成功
			// 退出登录
			session.invalidate();
			// 跳转到登录页面
			response.sendRedirect("login.jsp");
		} else {
			String error = "修改失败,未知错误！";
			if (res == -2) {
				error = "旧密码错误！";
			} else if (res == -3) {
				error = "2次新密码不一致！";
			} else if (res == -1) {
				error = "数据库操作失败！";
			}
			request.setAttribute("error", error);
			request.getRequestDispatcher("modifyPwd.jsp").forward(request, response);
		}
	}
	/**
	 * 上传头像
	 * @param request
	 * @param response
	 * @throws ServletException 
	 * @throws IOException 
	 */
	public void upload(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
		// 参数
		Part part = request.getPart("photo");
		// 字节输入流
		InputStream is = part.getInputStream();
		String path = request.getServletContext().getRealPath("upload");
		
		// 文件名，转换成字符串
		String fileName = UUID.randomUUID().toString();
		
		// 获取文件的后缀名,截取 . 后面的后缀
		String suffix = part.getSubmittedFileName().substring(part.getSubmittedFileName().lastIndexOf("."));
		
		// 组合文件名
		fileName = fileName + suffix;
		
		// 写入到服务器的硬盘上
		FileOutputStream fos = new FileOutputStream(path+"/"+fileName );
	
		byte[] buff = new byte[1024];
		
		while (true) {
			int length = is.read(buff);
			
			if(length < 0) {
				break;
			}
			
			fos.write(buff, 0, length);
		}
		fos.flush();
		fos.close();
		
		// 将文件名写入到数据库中
		// 当前登录用户
		User user = (User) request.getSession().getAttribute("user");
		// 调用userService 方法添加头像
		int res = userService.addPhoto(user.getId(),fileName);
		if(res > 0) {
			// 显示最新更改的图片
			user.setPhoto(fileName);
			// 上传成功
			response.sendRedirect("index.jsp");
		} else {
			// 上传失败
			request.setAttribute("error", "头像上传失败！");
			request.getRequestDispatcher("uploadPhoto.jsp").forward(request, response);
		}
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
